import config from '../config'
import router from '@/router'

let CACHE_TOKEN = config.CACHE_TOKEN

/** 随机生成固定位数或者一定范围内的字符串数字组合
 * @param {Number} min 范围最小值
 * @param {Number} max 范围最大值，当不传递时表示生成指定位数的组合
 * @param {String} charStr指定的字符串中生成组合
 * @returns {String} 返回字符串结果
 * */
function randomRange(min, max, charStr){
    var returnStr = "",
        range;
     if(typeof max == 'string'){
         charStr = max;
     }
     range = ((max && typeof max == 'number') ? Math.round(Math.random() * (max-min)) + min : min);
     charStr = charStr || 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
    for(var i=0; i<range; i++){
        var index = Math.round(Math.random() * (charStr.length-1));
        returnStr += charStr.substring(index,index+1);
    }
    return returnStr;
}
const randomNum = randomRange(10);

const getRole = ()=> {
    let role =  window.localStorage.getItem('userRole')
    switch(role){
        case 'guanli': return 1;
        case 'admin': return 2;
        case 'shenji': return 3;
        default: router.push({name: 'pageLogin'});  return false;
    }
}
const getUserId = ()=> window.localStorage.getItem('userId');
const setUserId = (userId) => window.localStorage.setItem('userId', userId)
// token
const getToken = (CACHE_TOKEN)=> {
    let fasleToken = window.localStorage.getItem(CACHE_TOKEN);
    let token = fasleToken.substring(10);
    return token;
}
const setToken = (token) => {
    window.localStorage.setItem(CACHE_TOKEN, randomNum + '' + token)
}
const removeToken =()=> window.localStorage.removeItem(CACHE_TOKEN)

const reLogin = ()=>{}
export {
    getRole,
    getUserId,
    setUserId,
    getToken,
    setToken,
    removeToken,
    reLogin
}